package com.ftg.wymall.util;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

/**
 * 图片类型
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/11/16 上午10:38
 */
public class FileUtils {

    public static final String IMAGE_PNG = "image/png";

    public static final String IMAGE_JPG = "image/jpg";

    public static final String IMAGE_JPEG = "image/jpeg";

    public static final String IMAGE_BMP = "image/bmp";

    public static final String IMAGE_GIF = "image/gif";

    public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};

    /**
     * 获取文件的扩展名
     * 如果文件的原文件名没有扩展名，则根据文件的Content-Type获取扩展名
     *
     * @param file 上传的文件
     * @return 文件的扩展名
     */
    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StrUtil.isEmpty(extension)) {
            extension = getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }

    /**
     * 获取文件的URL路径
     *
     * @param url 文件的URL
     * @return 文件名部分的URL
     * @throws RuntimeException 如果文件路径为空
     */
    public static final String getFileUrl(String url) {
        if (StrUtil.isEmpty(url)) {
            throw new RuntimeException("文件路径为空");
        }
        return url.substring(url.lastIndexOf("/") + 1);
    }

    /**
     * 获取文件扩展名
     *
     * @param prefix 文件前缀
     * @return 文件扩展名
     */
    public static String getExtension(String prefix) {
        switch (prefix) {
            case IMAGE_PNG:
                return "png";
            case IMAGE_JPG:
                return "jpg";
            case IMAGE_JPEG:
                return "jpeg";
            case IMAGE_BMP:
                return "bmp";
            case IMAGE_GIF:
                return "gif";
            default:
                return "";
        }
    }
}
